<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click="item='my-com1'">切换为组件1</button>
        <button @click="item='my-com2'">切换为组件2</button>
        <button @click="item='my-com3'">切换为组件3</button>
        <!-- <keep-alive include=""> 三种写法 
            include="component1,component2"
            :include="/component1|component2/"
            :include="['component1', 'component2']"
        -->
        <keep-alive include="component1,component2">
             <!-- 逗号后面一定不要加空格,让部分组件保留状态,避免组件的重新渲染 -->
        <!-- <keep-alive :include="/component1|component2/"> -->
        <!-- <keep-alive :include="['component1','component2']">     -->
            <component :is="item"></component>            
        </keep-alive>
    </div>

    <template id="com1">
        <div>
            <input type="text" v-model="aaa"> {{ aaa }}
            我是组件1 你可以看到我
        </div>
    </template>
    <template id="com2">
        <div>
            <input type="text" v-model="bbb"> {{ bbb }}
            我是组件2 你可以看到我

        </div>
    </template>
    <template id="com3">
        <div>
            <input type="text" v-model="ccc"> {{ ccc }}
            我是组件3 你可以看到我
        </div>
    </template>

    <script>

        const Com1 = {
            name: 'component1',
            template: '#com1',
            data() {
                return {
                    aaa: ''
                }
            }
        }

        const Com2 = {
            name: 'component2',
            template: '#com2',
            data() {
                return {
                    bbb: ''
                }
            }
        }
        const Com3 = {
            name: 'component3',
            template: '#com3',
            data() {
                return {
                    ccc: ''
                }
            }
        }
        new Vue({
            el: '#app',
            data: {
                item: 'my-com3'
            },
            components: {
                'myCom1': Com1,
                'myCom2': Com2,
                'myCom3': Com3,
            }
        })
    </script>
</body>
</html>